import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:qunaimedical/components/custom_avatar.dart';
import 'package:qunaimedical/components/item_option.dart';
import 'package:qunaimedical/components/item_quick_menu.dart';
import 'package:qunaimedical/components/primary_button.dart';
import 'package:qunaimedical/components/shimmer_indicator.dart';
import 'package:qunaimedical/im/im_utils.dart';
import 'package:qunaimedical/init/provider.dart';
import 'package:qunaimedical/models/me_menus.dart';
import 'package:qunaimedical/models/qa_user.dart';
import 'package:qunaimedical/network/http.dart';
import 'package:qunaimedical/pages/feedback.dart';
import 'package:qunaimedical/pages/profile.dart';
import 'package:qunaimedical/pages/web_page.dart';
import 'package:qunaimedical/utils/auth_util.dart';
import 'package:qunaimedical/utils/common_util.dart';
import 'package:qunaimedical/utils/dialog_util.dart';
import 'package:qunaimedical/utils/navigator_util.dart';
import 'package:qunaimedical/values/configs.dart';
import 'package:qunaimedical/values/navigation.dart';
import 'package:qunaimedical/values/urls.dart';

class MePage extends StatefulWidget {
  @override
  _MePageState createState() => _MePageState();
}

class _MePageState extends State<MePage> {
  RefreshController _refreshController = RefreshController();

  @override
  Widget build(BuildContext context) {
    QAUser? user = context.watch<StoreInfo>().qaUser;
    return Scaffold(
      backgroundColor: Colors.white,
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Container(
            height: MediaQuery.of(context).padding.top,
            color: Color(0xff39e7ba),
          ),
          Expanded(
            child: SmartRefresher(
              controller: _refreshController,
              enablePullUp: false,
              enablePullDown: true,
              header: ShimmerHeader(
                baseColor: Color(0xff39e7ba),
                text: Text(
                  "",
                  style: TextStyle(color: Colors.grey, fontSize: 22),
                ),
              ),
              onRefresh: user == null
                  ? () => _refreshController.refreshCompleted()
                  : _refresh,
              child: CustomScrollView(
                slivers: [
                  SliverToBoxAdapter(child: _buildHeader(context)),
                  _buildMenus(),
                  SliverToBoxAdapter(
                    child: ItemOption(
                      showTopBorder: true,
                      imagePath: 'assets/images/ic_feedback.png',
                      text: '后续反馈',
                      onTap: () => navigateTo(context, FeedbackPage()),
                    ),
                  ),
                  SliverToBoxAdapter(
                    child: ItemOption(
                      imagePath: 'assets/images/ic_about.png',
                      text: '关于我们',
                      onTap: () => navigateTo(
                          context, WebPage(url: Urls.ABOUT, title: "关于我们")),
                    ),
                  ),
                  SliverToBoxAdapter(
                    child: ItemOption(
                        imagePath: 'assets/images/ic_version.png',
                        text: '当前版本',
                        hideRightArrow: true,
                        trailing: FutureBuilder<PackageInfo>(
                          future: PackageInfo.fromPlatform(),
                          builder: ((BuildContext context,
                              AsyncSnapshot<PackageInfo> snapshot) {
                            String version = '';
                            if (snapshot.hasData) {
                              version =
                                  '${snapshot.data!.version} (${snapshot.data!.buildNumber})';
                            }
                            return Text(version,
                                style: Theme.of(context).textTheme.bodySmall);
                          }),
                        )),
                  ),
                  SliverToBoxAdapter(
                    child: Offstage(
                      offstage: user == null,
                      child: PrimaryButton(
                        '退出',
                        onPressed: () => _logout(context),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  void _logout(BuildContext context) {
    DialogUtil.showAlertDialog(context, '确认退出？', onPressed: () {
      Navigator.pop(context);
      AuthUtil.logout(context);
      IMUtils.signOut();
    });
  }

  void _refresh() async {
    QAUser user = context.read<StoreInfo>().qaUser!;
    String url = "${Urls.USER_INFO}${user.id}";
    try {
      Response response = await XHttp.instance.get(url);
      if (mounted) {
        if (response.statusCode == 200 &&
            response.data != null &&
            response.data["data"] != null) {
          user.name = response.data["data"]["name"];
          context.read<StoreInfo>().updateQAUser(user);
        }
      }
    } on DioError catch (e) {
      if (mounted) {
        CommonUtil.catchDioError(e);
      }
    }
    _refreshController.refreshCompleted();
  }

  Widget _buildHeader(BuildContext context) {
    QAUser? user = context.watch<StoreInfo>().qaUser;
    return Container(
      padding: EdgeInsets.only(
        top: 0,
        left: 16,
        right: 16,
        bottom: 0,
      ),
      height: 180,
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage("assets/images/bg_header.png"),
          fit: BoxFit.cover,
        ),
      ),
      child: Stack(
        alignment: Alignment.centerLeft,
        children: [
          Positioned(
            child: Offstage(
              offstage: user != null,
              child: InkWell(
                onTap: () {
                  navigateWithRoute(context, Navigation.login);
                },
                child: Text(
                  '登录/注册',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 24,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
            ),
          ),
          Positioned(
            child: Offstage(
              offstage: user == null,
              child: InkWell(
                onTap: () {
                  navigateTo(context, ProfilePage());
                },
                child: user == null
                    ? Container()
                    : Row(
                        children: [
                          CustomAvatar(size: 80, avatarUrl: user.photo),
                          SizedBox(width: 10),
                          Expanded(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                Text(
                                  user.name,
                                  maxLines: 1,
                                  style: TextStyle(
                                    color: Colors.white,
                                    fontSize: 24,
                                    fontWeight: FontWeight.bold,
                                  ),
                                  overflow: TextOverflow.ellipsis,
                                ),
                                _buildChip(user.companyId),
                                Container(
                                  padding: const EdgeInsets.only(top: 3),
                                  child: Row(
                                    children: [
                                      _buildChip(user.officeId),
                                      SizedBox(width: 8),
                                      _buildChip(user.level),
                                    ],
                                  ),
                                ),
                              ],
                            ),
                          ),
                          Icon(
                            Icons.chevron_right_outlined,
                            color: Colors.white,
                          )
                        ],
                      ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  void _goToPageWithUrl(String url) {
    navigateTo(context, WebPage(url: url), authStateRequired: true);
  }

  Widget _buildChip(String? value) {
    return Offstage(
      offstage: value == null || value == "",
      child: Container(
        margin: const EdgeInsets.only(top: 4.0),
        child: Text(
          value ?? "",
          style: TextStyle(fontSize: 12, color: Colors.white),
        ),
        padding: EdgeInsets.symmetric(
          horizontal: 8,
          vertical: 2,
        ),
        decoration: BoxDecoration(
          border: new Border.all(
            color: Colors.white,
            width: 0.5,
          ),
          borderRadius: new BorderRadius.all(Radius.circular(20)),
        ),
      ),
    );
  }

  bool isAssistant() {
    QAUser? user = context.read<StoreInfo>().qaUser;
    return user?.usertype == UserType.assistant.name;
  }

  bool isDoctor() {
    QAUser? user = context.read<StoreInfo>().qaUser;
    return user?.usertype == UserType.doctor.name;
  }

  bool isPatient() {
    QAUser? user = context.read<StoreInfo>().qaUser;
    return user?.usertype == UserType.patient.name;
  }

  Widget _buildMenus() {
    MeMenus? menuData = context.read<StoreInfo>().menus;
    if (menuData != null) {
      List<MenuItemA> menus = [];
      if (isDoctor()) {
        menus = menuData.doctor;
      } else if (isPatient()) {
        menus = menuData.patient;
      } else if (isAssistant()) {
        menus = menuData.assistant;
      } else {
        menus = menuData.admin;
      }
      return SliverGrid(
        delegate: SliverChildBuilderDelegate(
          (BuildContext context, int position) {
            final menu = menus[position];
            return ItemQuickMenu(
              imagePath: menu.imgResUrl,
              text: menu.btnText,
              onTap: () => _goToPageWithUrl(menu.imgTarget),
            );
          },
          childCount: menus.length,
        ),
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 4,
          childAspectRatio: MediaQuery.of(context).size.width > 600 ? 2 : 1.1,
        ),
      );
    } else {
      return Container();
    }
  }
}
